package com.vlin.api.client.request.tuya;

import com.vlin.api.client.Params;
import com.vlin.api.client.request.ParamsConfig;
import com.vlin.api.client.request.ParamsProducer;
import com.vlin.api.util.StringUtils;
import com.vlin.codec.HMACSHA256;
import com.vlin.constant.API;
import com.vlin.constant.TuyaAPIConstant;
import com.vlin.token.Token;

public class TuyaParamsProducer implements ParamsProducer {

	
	private ParamsConfig paramsConfig;
	
	private String clientId = TuyaAPIConstant.CLIENT_ID;
	
	private String secret = TuyaAPIConstant.SECRET;
	
	private String method = TuyaAPIConstant.SIGN_METHOD;

	@Override
	public boolean support(API api) {
		
		return API.TUYA.equals(api) || API.TUYA == api;
	}

	@Override
	public Params produce(API api) {
		
		return produce(api, "");
	}

	@Override
	public Params produce(API api, Token token) {
		
		return produce(api, token.getToken());
	}

	@Override
	public Params produce(API api, String token) {
		Params params = new Params();
		long t = System.currentTimeMillis();
		String data = (StringUtils.isBlankSpace(token) ? clientId + t : clientId + token + t);
		String sign = HMACSHA256.sha256_HMAC(data, secret).toUpperCase();
		params.setHeadParam("client_id",clientId);
		params.setHeadParam("sign", sign);
		params.setHeadParam("sign_method", method);
		params.setHeadParam("t", String.valueOf(t));
		if(StringUtils.isBlankSpace(token)) {
			params.setParam("grant_type", "1");
		} else {
			params.setHeadParam("access_token", token);
		}
		
		return params;
	}

	@Override
	public void setParamsConfig(API api, ParamsConfig paramsConfig) {
		if(support(api)) {
			this.paramsConfig = paramsConfig;
			if(paramsConfig.notContainsKey(TuyaAPIConstant.CLIENT_ID_NAME)) {
				throw new NullPointerException("Tuya ParamsConfig " + TuyaAPIConstant.CLIENT_ID_NAME + " is null");
			}
			if(paramsConfig.notContainsKey(TuyaAPIConstant.SECRET_NAME)) {
				throw new NullPointerException("Tuya ParamsConfig " + TuyaAPIConstant.SECRET_NAME + " is null");
			}
			if(paramsConfig.notContainsKey(TuyaAPIConstant.SIGN_METHOD_NAME)) {
				throw new NullPointerException("Tuya ParamsConfig " + TuyaAPIConstant.SIGN_METHOD_NAME + " is null");
			}
			this.clientId = this.paramsConfig.getStringValue(TuyaAPIConstant.CLIENT_ID_NAME);
			this.secret = this.paramsConfig.getStringValue(TuyaAPIConstant.SECRET_NAME);
			this.method = this.paramsConfig.getStringValue(TuyaAPIConstant.SIGN_METHOD_NAME);
		}
	}

}
